import { Component, OnInit, Output, EventEmitter } from "@angular/core";
import { MaintenancePlanBean } from "./../bean/maintenancePlanBan";
import { HttpServcie } from "./../../../service/http.service";
import { Config } from "./../../../service/config";
import { UploadFile, NzNotificationService } from "ng-zorro-antd";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import * as moment from "moment";

@Component({
  selector: "maintenance-plan-add-page",
  templateUrl: "maintenance-plan.add.html",
  styleUrls: ["maintenance-plan.add.scss"]
})
export class MaintenancePlanAdd implements OnInit {
  @Output() outValue = new EventEmitter();
  bean: MaintenancePlanBean = new MaintenancePlanBean();
  config: any = Config;
  validateForm: FormGroup;
  nzSpinning: boolean = false; //遮罩
  sysUser: any;
  startTime:any="";
  endTime:any="";

  constructor(
    private fb: FormBuilder,
    private httpService: HttpServcie,
    private _notification: NzNotificationService
  ) {
    this.sysUser = JSON.parse(window.localStorage.getItem("user"));
  }

  ngOnInit() {
    //设置下了框默认只为空
    this.validateForm = this.fb.group({
      discription: [null, [Validators.required]],
      planStartDate: [null, []],
      planEndDate: [null, []],
      startTime:[null, [Validators.required]],
      endTime:[null, [Validators.required]]

    });
  }

  submitForm() {
    this.bean.planStartDate = this.startTime;
    this.bean.planEndDate = this.endTime;
    this.bean.planStartDate = moment(this.bean.planStartDate).format("YYYY-MM-DD");
    this.bean.planEndDate = moment(this.bean.planEndDate).format("YYYY-MM-DD");
    console.log(this.bean);
    //没有填的标红
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    //处理是否提交
    for (const i in this.validateForm.controls) {
      if (!this.validateForm.controls[i].valid) {
        return;
      }
    }

    this.nzSpinning = true;
    if (this.fileList.length > 0) {
      let list: any = [];
      this.fileList.forEach(element => {
        list.push(element["response"]["data"]);
      });
      this.bean.url = list.toString();
    }
    if (!this.bean.url) {
      this._notification.create("warning","警告提示","请上传计划/方案附件！")
      this.nzSpinning = false;
      return;
    }
    this.bean.partyId = this.sysUser.partyId;
    this.httpService.maintenanceAdd(this.bean).subscribe(data => {
      this.nzSpinning = false;
      if (data["status"] != "200") {
        this._notification.create("error", "错误提示", "添加失败！");
        return;
      }
      this.outValue.emit(true);
    });
  }

  quit() {
    this.outValue.emit(true);
  }

  //文件上传
  previewImage = "";
  previewVisible = false;
  fileList: UploadFile[] = [];

  //查看
  handlePreview = (file: UploadFile) => {
    this.previewImage =
      this.config.IP + this.config.API.getUpload + file["response"]["data"] ||
      file.thumbUrl;
    this.previewVisible = true;
  };

  /**
   * 上传就开始调用
   * @param info
   */
  handleChange(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      this.fileList.forEach(element => {
        element["thumbUrl"] =
          this.config.IP +
          this.config.API.getUpload +
          element["response"]["data"];
      });
      // Get this url from response in real world.
    }
  }

  //移除文件
  nzRemoveFile = (file: UploadFile) => {
    this.httpService.deleteUpload(file["response"]["data"]).subscribe(
      data => {
        if (data["status"] != "200") {
          this._notification.create("error", "错误提示", "删除失败！");
          return;
        }
        //移除fileList中的数据
        if (this.fileList.length == 1) {
          this.fileList = [];
          return;
        }
        let list: UploadFile[] = [];
        this.fileList.forEach((element, index) => {
          if (element["thumbUrl"] == file.thumbUrl) {
            this.fileList.splice(index, 1);
            this.fileList = this.fileList;
            list = this.fileList;
            this.fileList = [];
          }
        });
        list.forEach(element => {
          this.fileList.push(element);
        });
      },
      error => {
        this._notification.create("error", "错误提示", "请求超时！");
        return;
      }
    );
  };
}
